package com.wxq.auth.service.impl;


import com.wxq.auth.feign.ThirdPartyFeignService;
import com.wxq.auth.service.SmsService;
import com.wxq.common.constant.AuthConstant;
import com.wxq.common.exception.BizCode;
import com.wxq.common.exception.RRException;
import com.wxq.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Jim
 * @date 6:45 下午 2022/4/10
 * @description 信息处理
 * @email:huwmz04153277@126.com
 */
@Slf4j
@Service("smsService")
public class SmsServiceImpl implements SmsService {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    private static final String SYMBOLS = "0123456789";
    //    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();


    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 数字验证码生成
     * @return
     */
    private String getCheckCode(){
        char[] nonceChars = new char[6];
        for (int i = 0; i < nonceChars.length; i++) {
            nonceChars[i] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 发送短信
     * @param mobile
     */
    @Override
    public void sendCode(String mobile) {
        //从缓存中获取验证码
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + mobile);
        if (!StringUtils.isEmpty(redisCode)){
            long codeTime = Long.parseLong(redisCode.split("_")[1]);
            //减少code相同情况带来的影响
            long currTime = System.currentTimeMillis();
            if (currTime - codeTime < 60000){
                //60秒不能再次发送验证码
                throw  new RRException(BizCode.SMS_CODE_EXCEPTION.getMessage(),BizCode.SMS_CODE_EXCEPTION.getCode());
            }
        }
        String code = getCheckCode();
        //验证码校验，将验证码放入redis中
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + mobile,
                code+"_"+System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        //发送验证码
        R r = thirdPartyFeignService.sendCode(mobile,code);
        if (r.getCode() != 0){
            log.error("调用远程服务    yomallthirdparty 发送短信验证码失败");
        }
    }

    /**
     * 校验验证码
     * @param mobile
     * @param code
     * @return
     */
    @Override
    public boolean checkCode(String mobile, String code) {
        String rediscode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + mobile);
        if (StringUtils.isEmpty(rediscode)){
            return false;
        } else {
            if (code.equals(rediscode.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + mobile);
                return true;
            } else {
                return false;
            }
        }
    }
}
